package org.yzh.web.service.impl;

import com.github.dozermapper.core.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.yzh.web.mapper.AlarmCountHourMapper;
import org.yzh.web.model.entity.AlarmCountHourDO;
import org.yzh.web.model.vo.AlarmCountHour;
import org.yzh.web.model.vo.AlarmCountHourQuery;
import org.yzh.web.service.AlarmCountHourService;

import java.time.LocalDate;
import java.time.LocalTime;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author lsj
 * @date 2021/1/17 1:28
 */
@Service
public class AlarmCountHourServiceImpl implements AlarmCountHourService {

    @Autowired
    private AlarmCountHourMapper alarmCountHourMapper;

    @Autowired
    private Mapper dozerMapper;

    @Override
    public List<AlarmCountHourDO> find(AlarmCountHourQuery query) {
        return alarmCountHourMapper.find(query);
    }

    @Override
    public List<AlarmCountHour> findAlarmCountHour(AlarmCountHourQuery query) {
        return find(query).stream().map( item -> dozerMapper.map(item, AlarmCountHour.class)).collect(Collectors.toList());
    }

    @Override
    public Optional<AlarmCountHourDO> findUnique(LocalDate date, LocalTime startHour, LocalTime endHour) {
        AlarmCountHourQuery query = new AlarmCountHourQuery();
        query.setStartDate(date);
        query.setEndDate(date);
        query.setStartHour(startHour);
        query.setEndHour(endHour);
        return this.find(query).stream().findFirst();
    }

    @Override
    public int insert(AlarmCountHourDO record) {
        return batchInsert(Collections.singletonList(record));
    }

    @Override
    public int batchInsert(List<AlarmCountHourDO> records) {
        return alarmCountHourMapper.batchInsert(records);
    }

    @Override
    public int update(AlarmCountHourDO record) {
        return alarmCountHourMapper.update(record);
    }

    @Override
    public int upsert(AlarmCountHourDO record) {
        Optional<AlarmCountHourDO> unique = findUnique(record.getDate(), record.getStartHour(), record.getEndHour());
        if (unique.isPresent()) {
            record.setId(unique.get().getId());
            return this.update(record);
        }
        return this.insert(record);
    }
}
